package com.unitedats.HR.Servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;

import com.unitedats.HR.Entity.HrDepartment;
import com.unitedats.common.Servlet.BasicServlet;
import com.unitedats.common.util.Common;
import com.unitedats.common.util.Default;
import com.unitedats.common.util.HtmlUtil;
import com.unitedats.common.util.WebUtil;

public class DepartmentAddDisplayServlet extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int parentId = WebUtil.getParamValueAsInteger(request, "parentId", 0);
		// int level = WebUtil.getParamValueAsInteger(request, "level", 0);

		if (parentId == 0) {
			request.setAttribute("rootDep", dbm.executeNamedQuery(HrDepartment.class, Default.NAMED_QUERY_FIND_ROOT)
					.get(0));
			forward(request, response, "HR/DepartmentAdd.jsp");
			return;
		}

		// ajax
		
		response.setContentType("application/json");

		HrDepartment searchCriteriaDepartment = new HrDepartment();
		searchCriteriaDepartment.setParentId(dbm.findById(parentId, HrDepartment.class));
		// searchCriteriaDepartment.setLevel(level);
		searchCriteriaDepartment.setStatus(true);

		List<HrDepartment> childs = dbm.find(searchCriteriaDepartment);
		if (parentId == Default.ROOT_DEPARTMENT_ID)
			childs.remove(dbm.findById(Default.ROOT_DEPARTMENT_ID, HrDepartment.class));

		if (childs != null && !childs.isEmpty()) {
			try {
				response.getWriter().print(HtmlUtil.getDepartmentListAsJSONArray(childs));
			} catch (JSONException e) {
				Common.log(e);
			}
		}

	}
}
